package com.ruoyi.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.domain.BoneCheck;
import com.ruoyi.domain.BoneCheck2;
import com.ruoyi.domain.Extcheck;
import com.ruoyi.domain.vo.*;
import com.ruoyi.mapper.*;
import com.ruoyi.service.BoneCheck2Service;
import com.ruoyi.service.BoneCheckService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@RestController
@Api(tags = "骨密度检查")
@SaCheckLogin

@RequestMapping(value = "/ray/bone_check/")
public class ApiBoneCheckController extends BaseController {

    @Autowired
    private BoneCheckMapper boneCheckMapper;

    @Autowired
    private BoneCheckUpdateMapper boneCheckUpdateMapper;

    @Autowired
    private BoneCheck2Mapper boneCheck2Mapper;


    @Autowired
    private ExtcheckMapper extcheckMapper;

//    @Autowired
//    private  ExtcheckMapper extcheckMapper;

    @ApiOperation("添加用户信息")
    @PostMapping("add_user")
    public AjaxResult add_user(@RequestBody BoneCheck2 boneCheckadd) {

        String dateStr = DateUtil.today();
        System.out.println("今天的日期是：" + dateStr);
        System.out.println("getIdCard = " + boneCheckadd.getIdCard());

        if (boneCheckadd.getIdCard() != null && boneCheckadd.getIdCard().length() > 10) {
//            return AjaxResult.success(boneCheckadd.getIdCard());
            //身份证处理
            if (!IdcardUtil.isValidCard(boneCheckadd.getIdCard())) {
                return AjaxResult.error("错误身份证");
            }

            System.out.printf("获取生日" + IdcardUtil.getBirthByIdCard(boneCheckadd.getIdCard()));

            System.out.printf("获取年龄" + IdcardUtil.getAgeByIdCard(boneCheckadd.getIdCard()));

            System.out.printf("获取出生年" + IdcardUtil.getYearByIdCard(boneCheckadd.getIdCard()));

            System.out.printf("获取出生月" + IdcardUtil.getMonthByIdCard(boneCheckadd.getIdCard()));

            System.out.printf("获取出生天" + IdcardUtil.getDayByIdCard(boneCheckadd.getIdCard()));

            System.out.printf("获取性别" + IdcardUtil.getGenderByIdCard(boneCheckadd.getIdCard()));

            System.out.printf("获取省份" + IdcardUtil.getProvinceByIdCard(boneCheckadd.getIdCard()));
            boneCheckadd.setBirthday(IdcardUtil.getBirthByIdCard(boneCheckadd.getIdCard()));
            boneCheckadd.setAge(IdcardUtil.getAgeByIdCard(boneCheckadd.getIdCard()));
            if (IdcardUtil.getGenderByIdCard(boneCheckadd.getIdCard()) == 1) {
                boneCheckadd.setSex("男");
            } else {
                boneCheckadd.setSex("女");
            }
        }

        boneCheckadd.setDate(new Date());
        boneCheckadd.setTime(new Date().getTime() / 1000);
        boneCheckadd.setUserId(StpUtil.getLoginIdAsInt());


        // 自定义日期格式
        String format = "yyyyMMdd";
        String todayStr = DateUtil.format(new Date(), format);
        System.out.println("今天的日期是：" + todayStr);

        QueryWrapper<BoneCheck2> where = new QueryWrapper<>();
        where.eq("date", dateStr);
        int 今天第几个 = boneCheck2Mapper.selectCount(where);


//
        boneCheckadd.setOrderSn(todayStr + Integer.toString(今天第几个 + 1));
        System.out.printf(String.valueOf(boneCheckadd));


        Integer res = boneCheck2Mapper.insert(boneCheckadd);

        BoneCheck3 newdata = BeanUtil.copyProperties(boneCheckadd, BoneCheck3.class);
        newdata.setDate(DateUtil.format(boneCheckadd.getDate(), "yyyy/MM/dd"));

        if (res > 0) {
            return AjaxResult.success("添加成功", newdata);
        } else {
            return AjaxResult.error("错误数据", newdata);
        }


    }

    // 此接口加上了 @SaIgnore 可以游客访问

    @PostMapping("update_user")
    @ApiOperation("更新用户信息")
    public AjaxResult 更新用户信息(@RequestBody BoneCheckUpdate boneCheck) {
        if (boneCheck.getId() != null) {
            BoneCheckUpdate old = boneCheckUpdateMapper.selectById(boneCheck.getId());
            if (old.getHeight() > 0 && old.getWeight() > 0) {
                //BMI = 体重（kg） / 身高（m）^2

                BigDecimal height = new BigDecimal(old.getHeight());
                height = height.divide(new BigDecimal(100));
                System.out.println(height);
                height = height.multiply(height);
                System.out.println(height);
                BigDecimal weight = new BigDecimal(old.getWeight());
                System.out.println(weight);
                BigDecimal bmi = weight.divide(height, 2);
                System.out.println(bmi);
                boneCheck.setBmi(bmi);
            }
        }


        Integer res = boneCheckUpdateMapper.updateById(boneCheck);
        if (res > 0) {
            return AjaxResult.success("更新成功", boneCheck);
        } else {
            return AjaxResult.error("更新失败", boneCheck);
        }

    }


    @PostMapping("update_user_ext")
    @ApiOperation("更新用户扩展信息")
    public AjaxResult 更新用户扩展信息(@RequestBody Extcheck extcheck) {


        if (extcheck.getCheckId() == null && extcheck.getOrderSn() == null) {
            return AjaxResult.error("请传递检查id或orderSn");
        }
        extcheck.setDate(new Date());

        if (extcheck.getCheckId() != null) {
            BoneCheck2 boneCheck2 = boneCheck2Mapper.selectById(extcheck.getCheckId());

            extcheck.setOrderSn(boneCheck2.getOrderSn());
            BoneCheck2 up = new BoneCheck2();
//            up.setBmd(extcheck.getCr2Bmd());

        }

        Extcheck old_extcheck = extcheckMapper.selectOne(new LambdaQueryWrapper<Extcheck>().eq(Extcheck::getCheckId, extcheck.getCheckId()));
        if (old_extcheck == null) {

            Integer res = extcheckMapper.insert(extcheck);
            if (res > 0) {
                return AjaxResult.success("插入成功", extcheck);
            } else {
                return AjaxResult.error("插入失败", extcheck);
            }
        } else {
            Integer res = extcheckMapper.updateById(extcheck);
            if (res > 0) {
                return AjaxResult.success("更新成功", extcheck);
            } else {
                return AjaxResult.error("更新失败", extcheck);
            }
        }


    }


    @Autowired
    private BoneCheckService boneCheckService;

    @Autowired
    private BoneCheck2Service boneCheck2Service;


    @SaIgnore
    @GetMapping("get_list")
    @ApiOperation("获取检查列表")
    public TableDataInfo 获取条件列表(@RequestParam(name = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                      @RequestParam(name = "pageSize", defaultValue = "2", required = false) Integer pageSize,
                                      BoneCheck boneCheck) {
        System.out.println("pageNum = " + pageNum);
        System.out.println("pageSize = " + pageSize);
        startPage();
        List<BoneCheck> list = boneCheckService.selectBoneCheckList(boneCheck);
        return getDataTable(list);

//
//        QueryWrapper<BoneCheck> qw = new QueryWrapper<>();
//        if(boneCheck.getAge()>0){
//            System.out.println(boneCheck);
//            qw.eq("age",boneCheck.getAge());
//        }
//        if(boneCheck.getBirthday().getTime()>0){
//            qw.eq("birthday",boneCheck.getBirthday());
//        }
//
//        if(boneCheck.getBmd()>0){
//            qw.eq("bmd",boneCheck.getBmd());
//        }
//
//        if(boneCheck.getBmdAge()>0){
//            qw.eq("bmd_age",boneCheck.getBmdAge());
//        }
//
//        if(boneCheck.getBmdMax()>0){
//            qw.eq("bmd_max",boneCheck.getBmdMax());
//        }
//
//        if(boneCheck.getBmi()>0){
//            qw.eq("bmi",boneCheck.getBmi());
//        }
//
////        if(boneCheck.getClinicalDiagnosis().length()>0){
////            qw.eq("clinical_diagnosis",boneCheck.getClinicalDiagnosis());
////        }
//
//        if(boneCheck.getDate().getTime()>0){
//            qw.eq("date",boneCheck.getDate());
//        }
//
//
//
//
//
//
//
//
//
//        PageInfo<BoneCheck> info = PageHelper.startPage(pageNum, pageSize)
//                .doSelectPageInfo(() -> boneCheckMapper.selectList(qw));
//
//        List<BoneCheck> list = info.getList();
//        return AjaxResult.success(String.valueOf(info.getTotal()),list);

    }


    @SaIgnore
    @GetMapping("get_list3")
    @ApiOperation("获取检查列表3")
    public AjaxResult 获取条件列表3(BoneCheckQuery query) {
        System.out.println("pageNum = " + query.getPageNum());
        System.out.println("pageSize = " + query.getPageSize());
        Page<BoneCheck2> page = new Page<>(query.getPageNum() == null ? 1 : query.getPageNum(), query.getPageSize() == null ? 10 : query.getPageSize());
        LambdaQueryWrapper<BoneCheck2> qw = new LambdaQueryWrapper<>();
//        System.out.println(query.getName());
//        System.out.println(StrUtil.isEmpty(query.getName()));
//        System.out.println("query.getName() != null");
//        System.out.println(query.getName() != null);
        qw.like(StrUtil.isNotEmpty(query.getName()), BoneCheck2::getName, query.getName());
        qw.eq(StrUtil.isNotEmpty(query.getSex()), BoneCheck2::getSex, query.getSex());
        qw.eq(StrUtil.isNotEmpty(query.getReferralDepartment()), BoneCheck2::getReferralDepartment, query.getReferralDepartment());
        qw.eq(StrUtil.isNotEmpty(query.getClinicalDiagnosis()), BoneCheck2::getClinicalDiagnosis, query.getClinicalDiagnosis());
        qw.eq(StrUtil.isNotEmpty(query.getSubmittingDoctor()), BoneCheck2::getSubmittingDoctor, query.getSubmittingDoctor());
        qw.eq(StrUtil.isNotEmpty(query.getInspectDoctor()), BoneCheck2::getInspectDoctor, query.getInspectDoctor());
        qw.eq(StrUtil.isNotEmpty(query.getReviewDoctor()), BoneCheck2::getReviewDoctor, query.getReviewDoctor());

        qw.eq(query.getAge() != null, BoneCheck2::getAge, query.getAge());
        qw.gt(query.getBeginAge() != null, BoneCheck2::getAge, query.getBeginAge());
        qw.lt(query.getEndAge() != null, BoneCheck2::getAge, query.getEndAge());

        qw.eq(query.getHeight() != null, BoneCheck2::getHeight, query.getHeight());
        qw.gt(query.getBeginHeight() != null, BoneCheck2::getHeight, query.getBeginHeight());
        qw.lt(query.getEndHeight() != null, BoneCheck2::getHeight, query.getEndHeight());

        qw.eq(query.getWeight() != null, BoneCheck2::getWeight, query.getWeight());
        qw.gt(query.getBeginWeight() != null, BoneCheck2::getWeight, query.getBeginWeight());
        qw.lt(query.getEndWeight() != null, BoneCheck2::getWeight, query.getEndWeight());

        qw.eq(query.getBmi() != null, BoneCheck2::getBmi, query.getBmi());
        qw.gt(query.getBeginBmi() != null, BoneCheck2::getBmi, query.getBeginBmi());
        qw.lt(query.getEndBmi() != null, BoneCheck2::getBmi, query.getEndBmi());


        qw.eq(query.getBmd() != null, BoneCheck2::getBmd, query.getBmd());
        qw.gt(query.getBeginBmd() != null, BoneCheck2::getBmd, query.getBeginBmd());
        qw.lt(query.getEndBmd() != null, BoneCheck2::getBmd, query.getEndBmd());


        qw.eq(query.getZ() != null, BoneCheck2::getZ, query.getZ());
        qw.gt(query.getBeginZ() != null, BoneCheck2::getZ, query.getBeginZ());
        qw.lt(query.getEndZ() != null, BoneCheck2::getZ, query.getEndZ());


        qw.eq(query.getT() != null, BoneCheck2::getT, query.getT());
        qw.gt(query.getBeginT() != null, BoneCheck2::getT, query.getBeginT());
        qw.lt(query.getEndT() != null, BoneCheck2::getT, query.getEndT());


        qw.eq(StrUtil.isNotEmpty(query.getDate()), BoneCheck2::getDate, query.getDate());
        qw.gt(StrUtil.isNotEmpty(query.getBeginDate()), BoneCheck2::getDate, query.getBeginDate());
        qw.lt(StrUtil.isNotEmpty(query.getEndDate()), BoneCheck2::getDate, query.getEndDate());
        System.out.println("qw = ");
        System.out.println(qw);


        Page page_data = boneCheck2Mapper.selectPage(page, qw);

        return AjaxResult.success(page_data);
//        LambdaQueryWrapper<BoneCheck2> qw = new LambdaQueryWrapper<>();
//        qw.gt(BoneCheck2::getAge,-1);
//        QueryWrapper qw = new QueryWrapper<>();
//            Page<BoneCheck2> page1 = boneCheck2Service.lambdaQuery().orderByDesc(BoneCheck2::getId).page(page);
//        IPage page2 = boneCheck2Service.page(page);
//        List list = page2.getRecords();
////
//
//        qw.orderByDesc(BoneCheck2::getId);
////        qw.orderByDesc("id");
//
//        List<BoneCheck2> list = boneCheck2Mapper.selectList(null);
//        long totalCount = page.getTotal();
//
//        System.out.println("totalCount = " + totalCount);


//        return AjaxResult.success(list);
    }

    @SaIgnore
    @PostMapping("get_list2")
    @ApiOperation("获取检查列表")
    public AjaxResult 获取列表(int pageNum, int pageSize) {

        PageInfo<BoneCheck> info = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> boneCheckMapper.selectList(null));

        List<BoneCheck> list2 = info.getList();
        List<BoneCheckVoExt> list = BeanUtil.copyToList(list2, BoneCheckVoExt.class);
        for (BoneCheckVoExt a :
                list) {
            Extcheck e = extcheckMapper.selectOne(new LambdaQueryWrapper<Extcheck>().eq(Extcheck::getCheckId, a.getId()));
            a.setExtcheck(BeanUtil.copyProperties(e, ExtcheckVo.class));
        }

        return AjaxResult.success(String.valueOf(info.getTotal()), list);

    }


    /**
     * 删除某条数据
     */
    @GetMapping("/detail")
    @ApiOperation("获取检查详情")
    public AjaxResult 详情(Integer id) {
        BoneCheck2 res = boneCheck2Mapper.selectById(id);

        BoneCheckVoExt boneCheck3 = BeanUtil.copyProperties(res, BoneCheckVoExt.class);
        Extcheck e = extcheckMapper.selectOne(new LambdaQueryWrapper<Extcheck>().eq(Extcheck::getCheckId, boneCheck3.getId()));
        boneCheck3.setExtcheck(BeanUtil.copyProperties(e, ExtcheckVo.class));

        if (res.getId() > 0) {
            return AjaxResult.success("", boneCheck3);
        } else {
            return AjaxResult.error("不存在", id);
        }
    }

    /**
     * 删除某条数据
     */
    @PostMapping("/remove")
    @ApiOperation("删除检查详情")
    public AjaxResult remove(Integer id) {
        Integer res = boneCheckMapper.deleteById(id);
        if (res > 0) {
            return AjaxResult.success("删除成功", id);
        } else {
            return AjaxResult.error("删除失败或不存在", id);
        }
    }


}
